package init

import (
	"encoding/json"
	"fmt"
	"github.com/nacos-group/nacos-sdk-go/clients"
	"github.com/nacos-group/nacos-sdk-go/common/constant"
	"github.com/nacos-group/nacos-sdk-go/vo"
	"github.com/spf13/viper"
	"go.uber.org/zap"
	"gorm.io/gorm/logger"
	"time"

	"goodServer/basic/config"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

func init() {
	InitZap()
	Viper()
	Nacos()
	Mysql()
}

var nacosread config.T

func Nacos() {
	conf := config.Nacosconfig.Nacos
	clientConfig := constant.ClientConfig{
		NamespaceId:         conf.NamespaceId, //we can create multiple clients with different namespaceId to support multiple namespace.When namespace is public, fill in the blank string here.
		TimeoutMs:           5000,
		NotLoadCacheAtStart: true,
		LogDir:              "/tmp/nacos/log",
		CacheDir:            "/tmp/nacos/cache",
		LogLevel:            "debug",
	}
	serverConfigs := []constant.ServerConfig{
		{
			IpAddr:      conf.Host,
			ContextPath: "/nacos",
			Port:        conf.Port,
			Scheme:      "http",
		},
	}
	configClient, _ := clients.CreateConfigClient(map[string]interface{}{
		"serverConfigs": serverConfigs,
		"clientConfig":  clientConfig,
	})

	content, err := configClient.GetConfig(vo.ConfigParam{
		DataId: conf.DataId,
		Group:  conf.Group},
	)
	if err != nil {
		panic(err)
	}
	zap.L().Info(fmt.Sprintf("content:%s", content))

	json.Unmarshal([]byte(content), &nacosread)
	zap.L().Info(fmt.Sprintf("nacosread:%s", nacosread))
}

func InitZap() {
	developmentConfig := zap.NewDevelopmentConfig()
	developmentConfig.OutputPaths = []string{"D:\\gocode\\src\\gao4\\4\\rk\\11\\good-list\\goodServer\\appzap.log"}
	build, err := developmentConfig.Build()
	if err != nil {
		return
	}
	zap.ReplaceGlobals(build)
}

func Mysql() {
	var err error
	nacosmysql := nacosread.Mysql
	// 参考 https://github.com/go-sql-driver/mysql#dsn-data-source-name 获取详情
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local",
		nacosmysql.User, nacosmysql.Pass, nacosmysql.Host, nacosmysql.Port, nacosmysql.Database)

	config.DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{
		Logger: logger.Default.LogMode(logger.Info),
	})
	if err != nil {
		panic(err)
	}
	sqlDB, err := config.DB.DB()

	// SetMaxIdleConns sets the maximum number of connections in the idle connection pool.
	sqlDB.SetMaxIdleConns(10)

	// SetMaxOpenConns sets the maximum number of open connections to the database.
	sqlDB.SetMaxOpenConns(100)

	// SetConnMaxLifetime sets the maximum amount of time a connection may be reused.
	sqlDB.SetConnMaxLifetime(time.Hour)
}

func Viper() {
	viper.SetConfigFile("./applocation.yaml")
	err := viper.ReadInConfig()
	if err != nil {
		panic(err)
	}
	err = viper.Unmarshal(&config.Nacosconfig)
	if err != nil {
		panic(err)
	}
	zap.L().Info(fmt.Sprintf("nacos:%s", config.Nacosconfig))
}
